import 'reflect-metadata';
import { getMetadataArgsStorage } from 'routing-controllers';
import { getPermissionMetaData } from '@utils/route-scanner';

export const PERM_KEY = 'Permission';

/** 打在 Controller 方法上，声明需要的权限码 */
export function RequiredPerm(code: string) {
  return function (target: any, propertyKey: string) {
    Reflect.defineMetadata(PERM_KEY, code, target, propertyKey);
  };
}

function extractTemplate(rawRoute: string, templates: string): string | null {
  const reg = templates.replace(/:\w+/g, '([^/]+)');
  if (new RegExp(`^${reg}$`).test(rawRoute)) return templates;
  return null;
}

export function getRequiredPerm(_method: string, _path: string): string | null {
  const storage = getMetadataArgsStorage();
  for (const action of storage.actions) {
    const { permCode, method, path } = getPermissionMetaData(storage, action);
    if (extractTemplate(_path, path) && action.type.toUpperCase() === method.toUpperCase()) return permCode;
  }
  return null; // 白名单或没打装饰器
}
